/**
 * Copyright ©2016-2022 tianyu education Corporation, All Rights Reserved
 * http://www.whty.com.cn/
 */
package profile.hujia.shiro.study.controller.config.shiro;

import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.ByteSource;
import org.springframework.beans.factory.annotation.Autowired;
import profile.hujia.shiro.study.model.UserDO;
import profile.hujia.shiro.study.model.UserStatusEnum;
import profile.hujia.shiro.study.service.UserService;

/**
 * class info
 *
 * @author hujia
 * @date 2019-12-09 16:39
 */
public class UserRealm extends AuthorizingRealm {

    @Autowired
    private UserService userService;

    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        return new SimpleAuthorizationInfo();
    }

    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        String userName = authenticationToken.getPrincipal().toString();
        UserDO userDO = userService.getUser(userName);
        if (userDO == null) {
            throw new UnknownAccountException();
        }
        if (userDO.getStatus().equals(UserStatusEnum.LOCKED)) {
            throw new LockedAccountException();
        }
        if (userDO.getStatus().equals(UserStatusEnum.DISABLED)) {
            throw new DisabledAccountException();
        }
        String salt = userDO.getSalt();
        SimpleAuthenticationInfo authenticationInfo = new SimpleAuthenticationInfo(userDO,
                userDO.getPassword(), ByteSource.Util.bytes(salt + userDO.getUserName()), getName());

        return authenticationInfo;
    }
}